# -*- encoding:utf-8 -*-
# @Time: 2022/11/3 14:28
# @Author : renyuxuan
# @Email: renyuxuan@maqu.com
# @File: permission.py
# @Software: PyCharm
from functools import update_wrapper
from rest_framework.permissions import BasePermission
from django.contrib.auth.models import Group


class TeacherPermission(BasePermission):
    def has_permission(self, request, view):
        """
        获取到当前发送请求的用户信息
        :param request:请求体
        :param view:
        :return:
        """
        user = request.user
        """
        判断身份，查询用户是不是在老师分组
        """
        gourp = Group.objects.filter(name='老师').first()
        usre_gourps = user.groups.all()
        return user.is_superuser or gourp in usre_gourps

class ActiveUserPermission(BasePermission):
    def has_permission(self, request, view):
        #操作的用户必须是当前登录的用户
        user = request.user
        return user.id == int(view.kwargs['pk'])

#更改权限装饰器
def wrap_permission(*permissions, validate_permission=True):
    def decorator(func):
        def wrapper(self, request, *args, **kwargs):
            self.permission_classes = permissions
            if validate_permission:
                self.check_permissions(request)
            return func(self, request, *args, **kwargs)
        return update_wrapper(wrapper, func)
    return decorator